package com.wu.family.space;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import com.idle.view.ProgressAroundView;
import com.wu.family.MainGroupActivity;
import com.wu.family.R;
import com.wu.family.amap.MapActLocationActivity;
import com.wu.family.config.Constant;
import com.wu.family.config.DeviceInfo;
import com.wu.family.config.Urls;
import com.wu.family.config.Urls.DataInfo;
import com.wu.family.config.UserInfo;
import com.wu.family.feed.FeedDetailActivity;
import com.wu.family.feed.FeedDetailDataUtil;
import com.wu.family.feed.FeedDetailImageActivity;
import com.wu.family.feed.FeedDetailListAdapter;
import com.wu.family.feed.FeedDetailListAdapter.OnItemClickInterface;
import com.wu.family.model.AudioPhoto;
import com.wu.family.model.UserComment;
import com.wu.family.more.MoreFamilyCardActivity;
import com.wu.family.publish.IConfigInfo;
import com.wu.family.utils.DisplayUtil;
import com.wu.family.utils.TimeUtil;
import com.wu.family.utils.TipsUtil;
import com.wu.family.utils.NetHelper;
import com.wu.family.utils.ToastUtil;
import com.wu.family.utils.WebViewUtil;
import com.wu.family.utils.WebViewUtil.OnWebLoadLintener;
import com.wu.family.utils.audio.SoundMgr;
import com.wu.family.utils.audio.SoundPlayer;
import com.wu.family.utils.audio.SoundMgr.SoundCallBack;
import com.wu.family.utils.audio.SoundPlayer.OnCompleteItf;
import com.wu.family.utils.json.JsonParse;
import com.wu.family.utils.json.MapBean;
import com.wu.family.utils.ze.LoadAvatarBmpMgr;
import com.wu.family.utils.ze.LoadBitmapMgr;
import com.wu.family.views.FooterView;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.AsyncTask;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.Animation.AnimationListener;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ImageView.ScaleType;
import android.widget.SlidingDrawer.OnDrawerCloseListener;
import android.widget.SlidingDrawer.OnDrawerOpenListener;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SlidingDrawer;
import android.widget.TextView;

public class SpaceViewPager2 extends RelativeLayout  implements ViewControllerImp, OnClickListener {
	
	private Context mContext;
	private ProgressBar progressBar;
	private LinearLayout llLlTitle;
	private TextView tvTitle;
	private ImageView ivIvAvatar;
	private ImageView ivVip;
	private LinearLayout llLlUserInfo;
	private TextView tvTvUserName;
	private TextView tvTvNickName;
	
	private TextView tvTvAlbumName;
	private ImageView ivLocation;
	private TextView tvTvTime;
	
	private LinearLayout llMiddle;
	// 2.3弃用
	//private SlidingDrawer commentDrawer;
//	private LinearLayout handle;
//	private Animation rightInAnimation;	
//	private Animation rightOutAnimation;
//	private TextView tvCommentNum;
	//private TextView tvTitle2;
	private TextView tvLoveUsers;
	private ListView lvListView;
	private RelativeLayout rlTips;
	
	private TextView tvContent;
	
	
	
	private FooterView footerView;
	//private SpaceDetailCommentAdapter mAdapter;
	private FeedDetailListAdapter mAdapter;
	private Map<String, Object> mMap;
	private List<UserComment> commentlist = new ArrayList<UserComment>();
	
	private Map<String, Object> feedContentMap;
	private ArrayList<String> photoUrls;
	private int interactNum;
	
	private String id;
	private String idtype;
	private String uid;
	private int page = 1;
	private int flag = 0;
	private boolean isLoading = false;
	
	private ImageView ivPic;
	private ImageView[] ivPicArray;
	private View llFeeddetailPic1, llFeeddetailPic4, llFeeddetailPicOther;
	TextView v2_3TvSpaceName ;
	TextView v2_3TvLovers;
	ImageButton	v2_3BtnReblog  		;
	ImageButton	v2_3BtnLove  		;
	ImageButton	v2_3BtnMore 		;
	private View 	v2_3DetailPicView;
	
	public SpaceViewPager2(Context context) {
		super(context);
		mContext = context;
		setupViews();
	}
	
	 public SpaceViewPager2(Context context, AttributeSet attrs) {  
	        super(context, attrs);  
	        mContext = context;
	        setupViews();  
	 } 
	//初始化View.  
    public void setupViews(){  
        LayoutInflater inflater = LayoutInflater.from(getContext());  
        View rootView = inflater.inflate(R.layout.space_detail_page, null);  
        v2_3DetailPicView = inflater.inflate(R.layout.feed_detail_pic_port_2_3, null);
        llFeeddetailPic1 = v2_3DetailPicView.findViewById(R.id.feeddetail_pic1);
        llFeeddetailPic4 = v2_3DetailPicView.findViewById(R.id.feeddetail_pic4);
        llFeeddetailPicOther = v2_3DetailPicView.findViewById(R.id.feeddetail_picOhter);
        
		lvListView = (ListView) rootView.findViewById( R.id.listView );
		progressBar = (ProgressBar)rootView.findViewById( R.id.progressBar );
		
//		commentDrawer = (SlidingDrawer) rootView.findViewById( R.id.commentDrawer );
//		handle = (LinearLayout) rootView.findViewById( R.id.handle );
		llLlTitle = (LinearLayout) rootView.findViewById( R.id.llTitle );
		tvTitle = (TextView) rootView.findViewById( R.id.tvTitle );
		
		ivIvAvatar = (ImageView) v2_3DetailPicView.findViewById( R.id.ivAvatar );
		ivVip = (ImageView) v2_3DetailPicView.findViewById( R.id.ivVip );
		tvTvUserName = (TextView) v2_3DetailPicView.findViewById( R.id.tvUserName );
		tvTvNickName = (TextView) v2_3DetailPicView.findViewById( R.id.tvNickName );
		tvTvTime = (TextView) v2_3DetailPicView.findViewById( R.id.tvTime );
		tvContent = (TextView)v2_3DetailPicView.findViewById(R.id.tvContent);
		
		llLlUserInfo = (LinearLayout) findViewById( R.id.llUserInfo );
		
		
		tvTvAlbumName = (TextView) rootView.findViewById( R.id.tvAlbumName );
		ivLocation = (ImageView) rootView.findViewById( R.id.ivLocation );
		
		llMiddle = (LinearLayout) rootView.findViewById( R.id.llMiddle );
		
		rlTips = (RelativeLayout) rootView.findViewById( R.id.rlTips );
		
		mAdapter = new FeedDetailListAdapter(mContext, commentlist);
		mAdapter.setOnItemClickInterface(new OnItemClickInterface() {
			@Override
			public void onComment(String message) {
				new postCommentTask(message).execute();
			}

			@Override
			public void onCommentClick(UserComment userComment) {
				Intent i = new Intent(Constant.Action.SPACE_COMMENT_CLICK_BROADCAST);
				i.putExtra("UserComment", userComment);
				mContext.sendBroadcast(i);
			}
		});
		// 2.3改造
		
		v2_3TvSpaceName 	= (TextView)v2_3DetailPicView.findViewById(R.id.v2_3tvDetail_spacename);
		v2_3TvLovers 		= (TextView)v2_3DetailPicView.findViewById(R.id.v2_3tvCommentTips);
		v2_3BtnReblog  		= (ImageButton)v2_3DetailPicView.findViewById(R.id.v2_3detail_btn_reblog);
		v2_3BtnLove  		= (ImageButton)v2_3DetailPicView.findViewById(R.id.v2_3detail_btn_like);
		v2_3BtnMore  		= (ImageButton)v2_3DetailPicView.findViewById(R.id.v2_3detail_btn_more);
		
		lvListView.addHeaderView(v2_3DetailPicView);
		lvListView.setAdapter(mAdapter);
		
		footerView = new FooterView(mContext);
		footerView.hideAll();
		lvListView.addFooterView(footerView.getFooter());
		
		llLlTitle.setOnClickListener( this );
		llMiddle.setOnClickListener(this);
		ivPic = (ImageView) rootView.findViewById(R.id.ivPic);
		
        addView(rootView);  
    }  
    
    @Override
	public void onClick(View v) {
    	if (v == llLlTitle || v == llMiddle) {
//			changeView();
		}else if( v == v2_3TvSpaceName ){
			// 跳到指定的空间瀑布流 
			// 如果是从空间瀑布流跳转过来的则不响应
			
		}else if( v == v2_3BtnLove ){
			// love
			v2_3BtnLove.setSelected( ! feedContentMap.get("mylove").equals("1"));
			((SpaceDetailActivity)mContext).v2_3makeLove(feedContentMap);
			
		}else if( v == v2_3BtnReblog ){
			// reblog
			((SpaceDetailActivity)mContext).v2_3repost(feedContentMap);
		}else if( v == v2_3BtnMore ){
			// 目前是share
			((SpaceDetailActivity)mContext).showSharePopupWindow();
		}
	}
   
    /** 
     * 填充数据，共外部调用. 
     * @param map 
     */  
    public void setData(Map<String, Object> map){  
        this.mMap = map;  
        if (mMap != null && mMap.size() > 0) {
        	id = (String)mMap.get("id");
            idtype = (String)mMap.get("idtype");
            uid = (String)mMap.get("uid");
            
            if (idtype!=null && !idtype.equals("")) {
    			if (!idtype.contains("id")) {
    				idtype = idtype + "id";
    			}
    			idtype = idtype.replace("re", "");
    		}else {
    			idtype = Constant.IdType.PHOTO_ID;
    		}
            if (idtype.contains(Constant.IdType.EVENT_ID)) {
    			//tvComment.setText("参加");
    		}
            tvTvUserName.setText((String)mMap.get("name"));
            
            page = mMap.get("page")!=null?(Integer)mMap.get("page"):1;
        	flag = mMap.get("flag")!=null?(Integer)mMap.get("flag"):0;
        	isLoading = false;
        	
        	if (mMap.get("feedContentMap")!=null) {
        		feedContentMap = (Map<String, Object>)mMap.get("feedContentMap");
        		setFeedContentData();
			}else {
				new GetFeedContentTask().execute();
			}
        	
        	if (mMap.get("mCommentlist")!=null) {
        		List<UserComment> tempList = (List<UserComment>)mMap.get("mCommentlist");
        		setCommentListData(tempList);
			}else {
				new GetFeedCommentListTask().execute();
			}
        	
		}
          
    }
    /** 
     * 这里内存回收.外部调用. 
     * 保存数据
     */  
    public void recycle(){  
    	mMap.put("page", page);
    	mMap.put("flag", flag);
    	mMap.put("feedContentMap", feedContentMap);
    	mMap.put("mCommentlist", commentlist);
    	((ImageView)v2_3DetailPicView.findViewById(R.id.feeddetail_pic1_pic)).setImageBitmap(null);
    	((ImageView)v2_3DetailPicView.findViewById(R.id.feeddetail_pic4_1_1)).setImageBitmap(null);
    	((ImageView)v2_3DetailPicView.findViewById(R.id.feeddetail_pic4_1_2)).setImageBitmap(null);
    	((ImageView)v2_3DetailPicView.findViewById(R.id.feeddetail_pic4_2_1)).setImageBitmap(null);
    	((ImageView)v2_3DetailPicView.findViewById(R.id.feeddetail_pic4_2_2)).setImageBitmap(null);
    	((ImageView)v2_3DetailPicView.findViewById(R.id.feeddetail_picOhter_1_1)).setImageBitmap(null);
    	((ImageView)v2_3DetailPicView.findViewById(R.id.feeddetail_picOhter_1_2)).setImageBitmap(null);
    	((ImageView)v2_3DetailPicView.findViewById(R.id.feeddetail_picOhter_1_3)).setImageBitmap(null);
    	((ImageView)v2_3DetailPicView.findViewById(R.id.feeddetail_picOhter_2_1)).setImageBitmap(null);
    	((ImageView)v2_3DetailPicView.findViewById(R.id.feeddetail_picOhter_2_2)).setImageBitmap(null);
    	((ImageView)v2_3DetailPicView.findViewById(R.id.feeddetail_picOhter_2_3)).setImageBitmap(null);
    	((ImageView)v2_3DetailPicView.findViewById(R.id.feeddetail_picOhter_3_1)).setImageBitmap(null);
    	((ImageView)v2_3DetailPicView.findViewById(R.id.feeddetail_picOhter_3_2)).setImageBitmap(null);
    	((ImageView)v2_3DetailPicView.findViewById(R.id.feeddetail_picOhter_3_3)).setImageBitmap(null);
    	llFeeddetailPic1.setVisibility(View.GONE);
    	llFeeddetailPic4.setVisibility(View.GONE);
    	llFeeddetailPicOther.setVisibility(View.GONE);
    }  
    /** 
     * 重新加载.外部调用. 
     */  
    public void reload(Map<String, Object> map){  
    	setData(map);
    }
    
    public void reloadComments(){
    	page = 1;
		flag = 0;
		isLoading = false;
		new GetFeedCommentListTask().execute();
    }
    
    private void executeTask() { 
		new GetFeedCommentListTask().execute();
		new GetFeedContentTask().execute();
	}
    
    class GetFeedCommentListTask extends AsyncTask<Object, Object, String>{
        
    	List<UserComment> tempList;
		boolean canLoad = true;
		protected void onPreExecute() {
			if (isLoading) {
				canLoad = false;
			}else {
				if(flag == 0){
					//showLoadingDialog();
				}else {
					//page = page + 1;
				}
				isLoading = true;
			}
			super.onPreExecute();
		}
		
		@Override
		protected String doInBackground(Object... params) {
			if (canLoad) {
				tempList = FeedDetailDataUtil.getCommentList(id, idtype, page);
				if (tempList != null ) {
					page++;
				}
			}
			
			
			return null;
		}
		
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (canLoad) {
				isLoading = false;
				if (flag == 0) {
					//hideLoadingDialog(); 
				}
				setCommentListData(tempList);
			}
		}
		
	}
	
    private void setCommentListData(List<UserComment> tempList){
    	if(tempList != null && tempList.size() > 0){
			if (flag == 0) {
				flag = 1;
				//mAdapter = new SpaceDetailCommentAdapter(mContext, tempList);
				mAdapter = new FeedDetailListAdapter(mContext, tempList);
				mAdapter.setOnItemClickInterface(new OnItemClickInterface() {
					//UserComment userComment;
					@Override
					public void onComment(String message) {
						new postCommentTask(message).execute();
					}

					@Override
					public void onCommentClick(UserComment userCmt) {
						Intent i = new Intent(Constant.Action.SPACE_COMMENT_CLICK_BROADCAST);
						i.putExtra("UserComment", userCmt);
						mContext.sendBroadcast(i);
						//TODO
						/*String hint = "评论";
						if (userComment == null 
								|| !userComment.getUser().getUid().equals(userCmt.getUser().getUid())) {
							hint = "回复"+userCmt.getUser().getName()+": ";
							etComment.requestFocus();
							etComment.setText("");
						}else if (userComment.getUser().getUid().equals(userCmt.getUser().getUid())
								&& !etComment.getText().toString().equals("")) {
							hint = "回复"+userCmt.getUser().getName()+": ";
						}
						//etComment.setHint(hint);
						userComment = userCmt;*/
					}
				});
				lvListView.setAdapter(mAdapter);
				
				lvListView.setOnScrollListener(new ScrollListener());
				commentlist = tempList;
				
			}else {
				commentlist.addAll(tempList);
				mAdapter.notifyDataSetChanged();
			}
			mMap.put("mCommentlist", commentlist);
			
			interactNum = commentlist.size();
			if (feedContentMap != null) {
				List<MapBean> loveuserMap = (List<MapBean>)feedContentMap.get("loveuser");
				if (loveuserMap != null && loveuserMap.size() > 0) {
					interactNum = interactNum + loveuserMap.size();
				}
			}
//			tvCommentNum.setText(interactNum + "条互动");
			//tvCommentNum.setText(commentlist.size() + "条互动");
		}else {
			if (tempList != null) {
				footerView.showNoData();
			}else {
				footerView.hideAll();
			}
		}
    }
    
	private class ScrollListener implements OnScrollListener
	{
		private int listViewLastItem = 0;
		private boolean isOver = false;
		@Override
		public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)
		{
			if (mAdapter.getCount() % 10 > 0 || mAdapter.getCount() == 0)
			{
				footerView.hideAll();
				isOver = true;
			}
			listViewLastItem = firstVisibleItem + visibleItemCount - 1; 
		}

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState)
		{    
			if (!isOver && !isLoading && listViewLastItem >= mAdapter.getCount()-5 
					&& scrollState == OnScrollListener.SCROLL_STATE_IDLE)
			{
				footerView.showLoading();
				new GetFeedCommentListTask().execute();
			}

		}
	}
    
	 private OnTouchListener onTouchlistener = new OnTouchListener() {
			
			float mLastY = 0;
			float mCurrentY = 0;
			float mMoveY = 0;
			boolean flag = false;
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					mLastY = mMoveY = event.getY();
					flag = false;
					break;
				case MotionEvent.ACTION_UP:
					mCurrentY = event.getY();
					if (Math.abs(mLastY - mCurrentY ) < 10 && !flag) {
//						changeView();
					}
					break;
				case MotionEvent.ACTION_MOVE:
					mCurrentY = event.getY();
					if (Math.abs(mCurrentY - mMoveY)  >= 10) {
						mMoveY = mCurrentY;
						if (!flag) {
							flag = true;
						}
					}
					break;
				default:
					break;
				}
				return false;
			}
		};
		
    class GetFeedContentTask extends AsyncTask<Object, Object, String>{
		private DataInfo dataInfo;

		protected void onPreExecute() {
			showLoadingDialog();
			dataInfo = new DataInfo();
			super.onPreExecute();
		}
		
		@Override
		protected String doInBackground(Object... params) {
			feedContentMap = FeedDetailDataUtil.getDataMap(idtype, uid, id, dataInfo);
			/*if (idtype.contains("photoid")){
				getPhotoContentMap();
			}else if (idtype.contains("blogid")) {
				getBlogContentMap();
			}else if (idtype.contains("videoid")) {
				getVideoContentMap();
			}else if (idtype.contains("eventid") ) {
				getEventContentMap();
			}*/
			return null;
		}
		
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			hideLoadingDialog(); 
			if(feedContentMap != null && feedContentMap.size() > 0){
	    		mMap.put("feedContentMap", feedContentMap);
	    		}
			setFeedContentData();
			
		}
	}
	
    private void setFeedContentData() {
    	if(feedContentMap != null && feedContentMap.size() > 0){
			/*new LoadImgTask(mContext, ivIvAvatar, 
					(String)feedContentMap.get("avatar"), R.drawable.head_70).execute();*/
    		ivIvAvatar.setImageBitmap(LoadAvatarBmpMgr.getInstance()
    				.loadBitmap((String)feedContentMap.get("avatar"), ivIvAvatar, null));
    		ivIvAvatar.setOnClickListener(new AvatarClickListener((String)feedContentMap.get("uid")));
    		
			tvTvUserName.setText((String)feedContentMap.get("name"));
			String vipstatus = (String)feedContentMap.get("vipstatus");
			if (!vipstatus.equals("")) {
				ivVip.setVisibility(View.VISIBLE);
				ivVip.setSelected(vipstatus.equals("family")?true:false);
			}else {
				ivVip.setVisibility(View.GONE);
			}
			
			String note = (String)feedContentMap.get("note");
			tvTvNickName.setText((note!=null&&!note.equals(""))?"("+note+")":"");
			tvTvTime.setText((String)feedContentMap.get("dateline"));
			
			String subject = (String)feedContentMap.get("subject");
			tvContent.setText(!subject.equals("")?subject:"无标题");
			//tvTitle2.setText((String)feedContentMap.get("message"));
			
			/*String repeatnum = (String)feedContentMap.get("repeatnum");
			String replynum = (String)feedContentMap.get("replynum");
			String love = (String)feedContentMap.get("love");*/
			
//			tvTvAlbumName.setText((String)feedContentMap.get("tagname"));
			v2_3TvSpaceName.setText((String)feedContentMap.get("tagname"));
			String loveuserNames = "";
			List<MapBean> loveuserMap = (List<MapBean>)feedContentMap.get("loveuser");
			if (loveuserMap != null && loveuserMap.size() > 0) {
				interactNum = loveuserMap.size();
				if (commentlist != null) {
					interactNum = interactNum + commentlist.size();
				}
//				tvCommentNum.setText(interactNum + "条互动");
				
				for (int i = 0; i < loveuserMap.size(); i++) {
					MapBean mapBean = loveuserMap.get(i);
					loveuserNames = loveuserNames + (String)mapBean.get("name") + ((i!=loveuserMap.size()-1)?",":"");
					if( mapBean.get("name").equals(UserInfo.getInstance(mContext).getName()) ){
						v2_3BtnLove.setSelected(true);
					}
				}
//				tvLoveUsers.setVisibility(View.VISIBLE); 
				v2_3TvLovers.setVisibility(View.VISIBLE);
			}else {
//				tvLoveUsers.setVisibility(View.GONE); 
				v2_3TvLovers.setVisibility(View.GONE);
			}
//			tvLoveUsers.setText(loveuserNames);
			v2_3TvLovers.setText(loveuserNames);
			feedContentMap.put("tvLoveUsers", v2_3TvLovers);
			
			v2_3DetailPicView.findViewById(R.id.llDiary).setVisibility(View.GONE);
			v2_3DetailPicView.findViewById(R.id.feeddetail_pic1).setVisibility(View.GONE);
			v2_3DetailPicView.findViewById(R.id.feeddetail_pic4).setVisibility(View.GONE);
			v2_3DetailPicView.findViewById(R.id.feeddetail_picOhter).setVisibility(View.GONE);
			if (idtype.contains("photoid")){
				llLlTitle.setVisibility(View.GONE); 
				String message = (String)feedContentMap.get("message");
				if (message.length() > 12) {
					//tvTitle2.setText(message);
					//tvTitle2.setVisibility(View.VISIBLE);
				}
				changeViewByOrientation();
				
			}else if (idtype.contains("blogid")) {
				llLlTitle.setVisibility(View.VISIBLE); 
				v2_3TvSpaceName.setOnClickListener(this);
				v2_3BtnLove.setOnClickListener(this);
				v2_3BtnMore.setOnClickListener(this);
				v2_3BtnReblog.setOnClickListener(this);
				//TODO:
				LinearLayout llDiary = (LinearLayout) v2_3DetailPicView.findViewById(R.id.llDiary);
				llDiary.setVisibility(View.VISIBLE);
				
				WebView webView = (WebView)v2_3DetailPicView.findViewById(R.id.wvDiary);
				
				WebViewUtil.config(mContext, webView, new OnWebLoadLintener() {
					@Override
					public void onReceivedTitle(String title) {}
					@Override
					public void onProgressChanged(int newProgress) {}
					@Override
					public void onPageStarted(String url) {
						showLoadingDialog();
					}
					@Override
					public void onPageFinished(String url) {
						hideLoadingDialog();
					}
					@Override
					public boolean onAppForwordUrl(String url) {
						/*if (url.matches(".*"+Constant.WebAppURL.TAILY_TOPIC)) {
							IConfigInfo configInfo = new IConfigInfo();
							configInfo.setIdtype(Constant.IdType.PHOTO_ID);
							configInfo.setTopicid((String)feedContentMap.get("topicid"));
							configInfo.setJoinTopic(true);
							
							showSelPhotoDialogToPub(configInfo, null, true);
							return true;
						}*/
						return false;
					}
				});
				/*WebSettings webSettings = webView.getSettings();
				webSettings.setJavaScriptEnabled(true);
				webSettings.setAllowFileAccess(true);
				webSettings.setDefaultTextEncodingName("utf-8");
				webSettings.setBuiltInZoomControls(false);
				webView.setWebViewClient(wvc);
				webView.setWebChromeClient(wvcc);*/	
				
				webView.setVisibility(View.VISIBLE); 
				webView.loadDataWithBaseURL(null, (String)feedContentMap.get("message"), 
						"text/html", "UTF-8", "about:blank");
				/*webView.setOnLongClickListener(new OnLongClickListener() {
					@Override
					public boolean onLongClick(View v) {
						changeView();
						return false;
					}
				});*/
				webView.setOnTouchListener(onTouchlistener);
				
				ImageView ivDiary = (ImageView) v2_3DetailPicView.findViewById(R.id.ivDiary);
				LoadBitmapMgr.getInstance().loadBitmap2((String)feedContentMap.get("diaryPic") + "!512", 
						ivDiary, 
            			new LoadBitmapMgr.ImageCallBack() {
							@Override
							public void setImage(Bitmap bitmap, String url, ImageView view) {
								//DisplayUtil.setImageLParamsByDrawable(FeedDetailActivity.this, view, d);
								if (url.equals((String)view.getTag())) {
									view.setScaleType(ScaleType.CENTER);
									view.setImageBitmap(bitmap);
								}
							}
						});
				
			}else if (idtype.contains("videoid")) {
				llLlTitle.setVisibility(View.VISIBLE); 
				
				View view = LayoutInflater.from(mContext).inflate(R.layout.feed_detail_item_pic_one, null);
				TextView tvContent = (TextView)view.findViewById(R.id.tvContent);
				ImageView ivPic = (ImageView)view.findViewById(R.id.pic);
				
				tvContent.setText((String)feedContentMap.get("message"));
				if (((String)feedContentMap.get("pic")).startsWith("http://")) {
					feedContentMap.put("wxPicUrl", (String)feedContentMap.get("pic"));
					
					ivPic.setImageBitmap(LoadBitmapMgr.getInstance().loadBitmap((String)feedContentMap.get("pic"), 
							ivPic,null));
							
					final String videourl = (String)feedContentMap.get("videourl");
					
					ivPic.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							Intent intent=new Intent();
							intent.setAction(Intent.ACTION_VIEW);
						    Uri CONTENT_URI_BROWSERS = Uri.parse(videourl.contains("http://")? videourl:"http://www.baidu.com");
						    intent.setData(CONTENT_URI_BROWSERS);
						    //intent.setClassName("com.android.browser", "com.android.browser.BrowserActivity");
						    mContext.startActivity(intent); 
						}
					});
				}else {
					ivPic.setImageDrawable(null);
					ivPic.setVisibility(View.GONE);
				}
				llMiddle.addView(view, new LayoutParams(LayoutParams.FILL_PARENT,
						LayoutParams.FILL_PARENT));
			}else if (idtype.contains("eventid") ) {
				llLlTitle.setVisibility(View.VISIBLE); 
				ivLocation.setVisibility(View.VISIBLE); 
				
				tvTitle.setText(!subject.equals("")?subject 
				   + "\n时间：" + (String)feedContentMap.get("starttime")
				   + "\n地点："+(String)feedContentMap.get("location"):"无标题");
				
				View view = LayoutInflater.from(mContext)
						.inflate(R.layout.feed_detail_act, null);
				WebView webView = (WebView)view.findViewById(R.id.webView);
				WebViewUtil.config(mContext, webView, new OnWebLoadLintener() {
					@Override
					public void onReceivedTitle(String title) {}
					@Override
					public void onProgressChanged(int newProgress) {}
					@Override
					public void onPageStarted(String url) {
						showLoadingDialog();
					}
					@Override
					public void onPageFinished(String url) {
						hideLoadingDialog();
					}
					@Override
					public boolean onAppForwordUrl(String url) {
						/*if (url.matches(".*"+Constant.WebAppURL.TAILY_TOPIC)) {
							IConfigInfo configInfo = new IConfigInfo();
							configInfo.setIdtype(Constant.IdType.PHOTO_ID);
							configInfo.setTopicid((String)feedContentMap.get("topicid"));
							configInfo.setJoinTopic(true);
							
							showSelPhotoDialogToPub(configInfo, null, true);
							return true;
						}*/
						return false;
					}
				});
				/*WebSettings webSettings = webView.getSettings();
				webSettings.setJavaScriptEnabled(true);
				webSettings.setAllowFileAccess(true);
				webSettings.setDefaultTextEncodingName("utf-8");
				webSettings.setBuiltInZoomControls(false);
				webView.setWebViewClient(wvc);
				webView.setWebChromeClient(wvcc);*/
				
				webView.setVisibility(View.VISIBLE); 
				webView.loadDataWithBaseURL(null, (String)feedContentMap.get("detail"), 
						"text/html", "UTF-8", "about:blank");
				/*webView.setOnLongClickListener(new OnLongClickListener() {
					@Override
					public boolean onLongClick(View v) {
						changeView();
						return false;
					}
				});*/
				webView.setOnTouchListener(onTouchlistener);
				
				llMiddle.removeAllViews();
				llMiddle.addView(view, new LayoutParams(LayoutParams.FILL_PARENT,
						LayoutParams.FILL_PARENT));
				
				if (((String)feedContentMap.get("poster")).startsWith("http://")) {
					feedContentMap.put("wxPicUrl", (String)feedContentMap.get("poster"));
				}else {
				}
				ivLocation.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						Intent intent = new Intent(mContext, MapActLocationActivity.class);
						intent.putExtra("latitude", (String)feedContentMap.get("lat"));
						intent.putExtra("longitude", (String)feedContentMap.get("lng"));
						intent.putExtra("locationName", (String)feedContentMap.get("location"));
						mContext.startActivity(intent);
					}
				});
			}
			
		}else {
			TipsUtil.showNetToast(mContext);
		}
    }
    
    class postCommentTask extends AsyncTask<Integer, Integer, String>{
		String jsonStr;
		String message;
		public postCommentTask(String message) {
			super();
			this.message = message;
		}
		
		@Override
		protected void onPreExecute() {
			//showLoadingDialog();
			ToastUtil.show(mContext, "发送中...");
			super.onPreExecute();
		}


		@Override
		protected String doInBackground(Integer... params) {
			jsonStr = postComment(message);
			return null;
		}
		
		protected void onPostExecute(String str){
			//hideLoadingDialog();
			if(jsonStr!= null && !"".equals(jsonStr.trim())){
				try{
					JSONObject result = new JSONObject(jsonStr);
					if(result.getInt("error") == 0){
						interactNum++;
//						tvCommentNum.setText(interactNum+"条互动");
						
						ToastUtil.show(mContext, "评论成功！");
						reloadComments();
					}else {
						ToastUtil.show(mContext, result.getString("msg"));
					}
				}catch(Exception e){
					e.printStackTrace();
				}

			}else {
				TipsUtil.showUploadFailToast(mContext);
			}
		}
	}
	
	private String postComment(String message){
		HashMap<String, String> map = new HashMap<String, String>();
	    map.put("id", id);
		map.put("idtype", idtype);
		map.put("message", message);
		map.put("m_auth", Urls.M_AUTH);
		
		List<NameValuePair> requestList = new ArrayList<NameValuePair>();
		NameValuePair item;
		
		Set<String> keySet = map.keySet();
		for (String key : keySet) {
			String value = map.get(key);
			item = new BasicNameValuePair(key, value);
			requestList.add(item);
		}
		
		return NetHelper.post(Urls.getComment(), requestList);
	}
    
    @Override
  	public void onConfigurationChanged(Configuration newConfig) {
  		
    	/*int t = this.getResources().getConfiguration().orientation ;
	       if(t == Configuration.ORIENTATION_LANDSCAPE){
	           //setContentView(R.layout.feed_detail_land);
	    	   ViewGroup.LayoutParams lParams2 = commentDrawer.getLayoutParams();
	    	   lParams2.width = DisplayUtil.dip2px(mContext, 400);
	    	   commentDrawer.setLayoutParams(lParams2);
	           
	       } else if(t ==Configuration.ORIENTATION_PORTRAIT){
	           //setContentView(R.layout.feed_detail);
	    	   ViewGroup.LayoutParams lParams2 = commentDrawer.getLayoutParams();
	    	   lParams2.width = ViewGroup.LayoutParams.FILL_PARENT;
	    	   commentDrawer.setLayoutParams(lParams2);
	    	   
	       }*/
//	    changeDrawerByOrientation();
	    changeViewByOrientation();
		super.onConfigurationChanged(newConfig);
  	}
     /**
      * 2.3弃用
      
    private void changeDrawerByOrientation() {
		int t = this.getResources().getConfiguration().orientation ;
	       if(t == Configuration.ORIENTATION_LANDSCAPE){
	    	   ViewGroup.LayoutParams lParams2 = commentDrawer.getLayoutParams();
	    	   lParams2.width = DisplayUtil.dip2px(mContext, 400);
	    	   commentDrawer.setLayoutParams(lParams2);
	    	   
	    	   ViewGroup.LayoutParams lParams3 = handle.getLayoutParams();
	    	   lParams3.height = MainGroupActivity.screenWidth-DisplayUtil.dip2px(mContext, 138);
	    	   handle.setLayoutParams(lParams3);
	           
	       } else if(t ==Configuration.ORIENTATION_PORTRAIT){
	    	   ViewGroup.LayoutParams lParams2 = commentDrawer.getLayoutParams();
	    	   lParams2.width = ViewGroup.LayoutParams.FILL_PARENT;
	    	   commentDrawer.setLayoutParams(lParams2);
	    	   
	    	   ViewGroup.LayoutParams lParams3 = handle.getLayoutParams();
	    	   lParams3.height = MainGroupActivity.screenHeight-DisplayUtil.dip2px(mContext, 138);
	    	   handle.setLayoutParams(lParams3);
	       }
	}
    */
    private void changeViewByOrientation() {
		if(feedContentMap != null && feedContentMap.size() > 0){
			if (idtype.contains("photoid")){
				List<Map<String, String>> list = (List<Map<String, String>>)feedContentMap.get("piclist");
				photoUrls = new ArrayList<String>();
				
				if (list != null && list.size() > 0) {
					
					/*******************************/
					  // 2.3详情改造
					/*******************************/
					// 支持显示9张图片
					ivPicArray = new ImageView[9];
					
//					v2_3DetailPicView = LayoutInflater.from(mContext)
//	    			   .inflate(R.layout.feed_detail_pic_port_2_3, null);
					v2_3TvSpaceName.setOnClickListener(this);
					v2_3BtnLove.setOnClickListener(this);
					v2_3BtnMore.setOnClickListener(this);
					v2_3BtnReblog.setOnClickListener(this);
					
					ivPicArray[0] = (ImageView)v2_3DetailPicView.findViewById(R.id.feeddetail_picOhter_1_1);
					ivPicArray[1] = (ImageView)v2_3DetailPicView.findViewById(R.id.feeddetail_picOhter_1_2);
					ivPicArray[2] = (ImageView)v2_3DetailPicView.findViewById(R.id.feeddetail_picOhter_1_3);
					ivPicArray[3] = (ImageView)v2_3DetailPicView.findViewById(R.id.feeddetail_picOhter_2_1);
					ivPicArray[4] = (ImageView)v2_3DetailPicView.findViewById(R.id.feeddetail_picOhter_2_2);
					ivPicArray[5] = (ImageView)v2_3DetailPicView.findViewById(R.id.feeddetail_picOhter_2_3);
					ivPicArray[6] = (ImageView)v2_3DetailPicView.findViewById(R.id.feeddetail_picOhter_3_1);
					ivPicArray[7] = (ImageView)v2_3DetailPicView.findViewById(R.id.feeddetail_picOhter_3_2);
					ivPicArray[8] = (ImageView)v2_3DetailPicView.findViewById(R.id.feeddetail_picOhter_3_3);
					// 根据照片数量设置布局
					if( list.size() == 1 ){
						// 一张的情况
						
						llFeeddetailPic1.setVisibility(View.VISIBLE);
						
						ivPicArray[0] = (ImageView)v2_3DetailPicView.findViewById(R.id.feeddetail_pic1_pic);
						ViewGroup.LayoutParams lp = ivPicArray[0].getLayoutParams();
						lp.height = MainGroupActivity.screenWidth - 2 * 10 * (DeviceInfo.DENSITYDPI/160);
						//ivPicArray[0].setLayoutParams(lp);
						
					}else if( list.size() == 4 || list.size() == 2){
						// 4张的情况
						
						llFeeddetailPic4.setVisibility(View.VISIBLE);
						if (list.size() == 4) {
							v2_3DetailPicView.findViewById(R.id.feeddetail_pic4_2).setVisibility(View.VISIBLE);
						}else {
							v2_3DetailPicView.findViewById(R.id.feeddetail_pic4_2).setVisibility(View.GONE);
						}
						ivPicArray[0] = (ImageView)v2_3DetailPicView.findViewById(R.id.feeddetail_pic4_1_1);
						ivPicArray[1] = (ImageView)v2_3DetailPicView.findViewById(R.id.feeddetail_pic4_1_2);
						ivPicArray[2] = (ImageView)v2_3DetailPicView.findViewById(R.id.feeddetail_pic4_2_1);
						ivPicArray[3] = (ImageView)v2_3DetailPicView.findViewById(R.id.feeddetail_pic4_2_2);
						
						// 高=屏幕宽度-图片的左右pading（20）-图片之间的缝隙（15）再除以3
						int len = ( MainGroupActivity.screenWidth - 15 * DeviceInfo.DENSITYDPI / 160 )/2;
						ViewGroup.LayoutParams lp;
						for (int i = 0; i < 4; i++) {
							lp = ivPicArray[i].getLayoutParams();
							lp.width = lp.height = len;
						}
					}else{
						// 其他情况 一行3张
						
						llFeeddetailPicOther.setVisibility(View.VISIBLE);
						if( list.size() > 3 ){
							v2_3DetailPicView.findViewById(R.id.feeddetail_picOhter_2).setVisibility(View.VISIBLE);
						}else {
							v2_3DetailPicView.findViewById(R.id.feeddetail_picOhter_2).setVisibility(View.GONE);
						}
						if( list.size() > 6 ){
							v2_3DetailPicView.findViewById(R.id.feeddetail_picOhter_3).setVisibility(View.VISIBLE);
						}else {
							v2_3DetailPicView.findViewById(R.id.feeddetail_picOhter_3).setVisibility(View.GONE);
						}
						
						// 高=屏幕宽度-图片的左右pading（20）-图片之间的缝隙（20）再除以3
						int len = (int)(( MainGroupActivity.screenWidth - 30 * DeviceInfo.DENSITYDPI / 160 )/3);
						System.out.println("i need:" + len);
						ViewGroup.LayoutParams lp = ivPicArray[0].getLayoutParams();
						//len = lp.width;
						for (int j = 0; j < ivPicArray.length; j++) {
							lp = ivPicArray[j].getLayoutParams();
							lp.width = lp.height = len;
						}
					}
					OnClickListener onClickListener = null;
					for (int i = 0; i < list.size(); i++) {
						if (i >= 9) {
							break;
						}
						ivPicArray[i].setVisibility(View.VISIBLE);
					}
					for (int i = list.size(); i < ivPicArray.length; i++) {
						ivPicArray[i].setVisibility(View.GONE);
					}
					for (int index = 0; index < list.size(); index++) {
						if( index >= 9 ){
							break;
						}
						Map<String, String> map = list.get(index);
						photoUrls.add((String)map.get("pic"));
						String picUrl = (String)map.get("pic");
						if (list.size() > 1 && picUrl.contains("!")) {
							if (DeviceInfo.SCREEN_WIDTH > 700) {
								picUrl = picUrl.split("!")[0] + "!190X190";
							}else {
								picUrl = picUrl.split("!")[0] + "!120X120";
							}
						}else if (list.size() > 1 && picUrl.contains("http")) {
							if (DeviceInfo.SCREEN_WIDTH > 700) {
								picUrl = picUrl + "!190X190";
							}else {
								picUrl = picUrl + "!120X120";
							}
						}
						if (list.size() == 1 && picUrl.contains("!")) {
							if (DeviceInfo.SCREEN_WIDTH > 700) {
								picUrl = picUrl.split("!")[0] + "!600";
							}else {
								picUrl = picUrl.split("!")[0] + "!376";
							}
						}else if (list.size() == 1 && picUrl.contains("http")) {
							if (DeviceInfo.SCREEN_WIDTH > 700) {
								picUrl = picUrl + "!600";
							}else {
								picUrl = picUrl + "!376";
							}
						}
						map.put("pic", picUrl);
						LoadBitmapMgr.getInstance().loadBitmap2(picUrl, 
								ivPicArray[index], 
		            			new LoadBitmapMgr.ImageCallBack() {
									@Override
									public void setImage(Bitmap bitmap, String url, ImageView view) {
										//DisplayUtil.setImageLParamsByDrawable(FeedDetailActivity.this, view, d);
										if (url.equals((String)view.getTag())) {
											view.setImageBitmap(bitmap);
										}
									}
								});
//						final int showIndex = index; 
						if (index == 0) {
							
							onClickListener = new OnClickListener() {
								@Override
								public void onClick(View v) {
									Intent intent = new Intent(mContext, FeedDetailImageActivity.class);
									//intent.putExtra("picurl", (String)map.get("pic"));
									intent.putExtra("uid", (String)feedContentMap.get("uid"));
									intent.putExtra("idtype", idtype);
									int pos = 0;
									for (int i = 0; i < ivPicArray.length; i++) {
										if( ivPicArray[i].equals(v) ){
											pos = i;
											break;
										}
									}
									intent.putExtra("showIndex", pos);
									intent.putExtra("photoid", (String)feedContentMap.get("photoid"));
									intent.putExtra("message", (String)feedContentMap.get("message"));
									intent.putStringArrayListExtra("photoUrls", photoUrls);
									intent.putExtra("AudioPhoto", (AudioPhoto)feedContentMap.get("AudioPhoto"));
									mContext.startActivity(intent);
								}
							};
							
							feedContentMap.put("wxPicUrl", (String)map.get("pic"));
							
//							    
							
							final ProgressAroundView btnPlayOrPause = (ProgressAroundView) v2_3DetailPicView.findViewById( R.id.btnPlayOrPause );
							
							
							v2_3BtnLove.setSelected(feedContentMap.get("mylove").equals("1")?true:false);
							llMiddle.removeAllViews();
							//ivAvatar.setOnClickListener(new AvatarClickListener((String)feedContentMap.get("uid")));
							//tvUserName.setOnClickListener(new AvatarClickListener((String)feedContentMap.get("uid")));
							
							final AudioPhoto audioPhoto = (AudioPhoto)feedContentMap.get("AudioPhoto");
							if (audioPhoto != null && !audioPhoto.getAudioUrl().equals("")) {
								
								btnPlayOrPause.setVisibility(View.VISIBLE);
								if (audioPhoto.isPlaying()) {
									btnPlayOrPause.setImageResource(R.drawable.feed_btn_audiopause);
									btnPlayOrPause.setTotalTime(SoundPlayer.getInstance().getDuration());//audioPhoto.getAudioTime()*1000);
									btnPlayOrPause.setProgressAndStartTiming(SoundPlayer.getInstance().getProgress());
								}else {
									btnPlayOrPause.setImageResource(R.drawable.feed_btn_audioplay);
								}
								btnPlayOrPause.setOnClickListener(new OnClickListener() {
									@Override
									public void onClick(View v) {
										if (audioPhoto.isPlaying()) {
											btnPlayOrPause.stopTiming();
											btnPlayOrPause.setProgress(0);
											SoundPlayer.getInstance().stop();
											audioPhoto.setPlaying(false);
											btnPlayOrPause.setImageResource(R.drawable.feed_btn_audioplay);
										}else {
											SoundMgr.getInstance().getSoundPath(audioPhoto.getAudioUrl(), new SoundCallBack(){
												@Override
												public void onFoundCachePath(String url, String path) {
													SoundPlayer.getInstance().playMusic(path, new OnCompleteItf() {
														@Override
														public void OnPreStart(int duration) {
															audioPhoto.setPlaying(true);
															btnPlayOrPause.setImageResource(R.drawable.feed_btn_audiopause);
															Intent intent = new Intent(Constant.Action.START_SOUND_BROADCAST);
															mContext.sendBroadcast(intent);
															btnPlayOrPause.setTotalTime(duration!=-1?duration:audioPhoto.getAudioTime()*1000);
															btnPlayOrPause.startTiming();
														}
														@Override
														public void OnComplete() {
															btnPlayOrPause.setProgress(0);
															btnPlayOrPause.stopTiming();
															btnPlayOrPause.setImageResource(R.drawable.feed_btn_audioplay);
															audioPhoto.setPlaying(false);
														}

														@Override
														public void OnUnComplete() {
															btnPlayOrPause.setProgress(0);
															btnPlayOrPause.stopTiming();
															btnPlayOrPause.setImageResource(R.drawable.feed_btn_audioplay);
															audioPhoto.setPlaying(false);
														}
													});
												}});
										}
									}
								});
							}else {
								btnPlayOrPause.setVisibility(View.GONE);
							}
						}// end of index == 0 
						if( onClickListener != null ){
							ivPicArray[index].setOnClickListener(onClickListener);
						}
					}// end of for
					mAdapter.notifyDataSetChanged();
					feedContentMap.put("photoUrls", photoUrls);
				}else {
					llLlTitle.setVisibility(View.VISIBLE);
				}
			}
		}
	}
    
    class AvatarClickListener implements OnClickListener{
		String uid;
		public AvatarClickListener(String uid) {
			super();
			this.uid = uid;
		}
		@Override
		public void onClick(View v) {
			Intent intent = new Intent(mContext, MoreFamilyCardActivity.class);
			intent.putExtra("uid", uid);
			mContext.startActivity(intent);
		}
	}
    
  	private void hideLoadingDialog(){
  		if (progressBar != null && progressBar.isShown()) {
  			progressBar.setVisibility(View.GONE);
  		}
  	}

	private void showLoadingDialog(){
		if (progressBar == null) {
			return ;
		}
		progressBar.setVisibility(View.VISIBLE);
	}

}
